package cn.hist.hfp.service;

import cn.hist.hfp.converter.StrayConverter;
import cn.hist.hfp.entity.Stray;
import cn.hist.hfp.exception.ResourceNotFoundException;
import cn.hist.hfp.repository.StrayRepository;
import cn.hist.hfp.vo.StrayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StrayService {

    @Value(value = "${hfp.page-size.stray}")
    private int pageSize;

    private final
    StrayRepository strayRepository;

    private final StrayConverter strayConverter;

    @Autowired
    public StrayService(StrayRepository strayRepository, StrayConverter strayConverter) {
        this.strayRepository = strayRepository;
        this.strayConverter = strayConverter;
    }

    public Stray create(Stray stray) {
        return strayRepository.save(stray);
    }

    public StrayVO findOneVO(int id) {
        return strayConverter.convert(findOne(id));
    }

    public Stray findOne(int id) {
        Optional<Stray> optionalStray = strayRepository.findById(id);
        if (optionalStray.isPresent()) {
            return optionalStray.get();
        }
        throw new ResourceNotFoundException();
    }


    public List<StrayVO> findSome(int page) {
        return strayConverter.convert(
                strayRepository.findAll(PageRequest.of(page, pageSize, Sort.by("id").descending())).getContent());
    }

    public int numberOfPages() {
        return strayRepository.findAll(PageRequest.of(0, pageSize)).getTotalPages();
    }

    public StrayVO update(Stray stray) {
        return strayConverter.convert(strayRepository.save(stray));
    }

    public int delete(int id) {
        Optional<Stray> optionalStray = strayRepository.findById(id);
        optionalStray.ifPresent(strayRepository::delete);
        return strayRepository.findById(id).isPresent() ? 0 : 1;
    }
}
